import Vue from "vue";
import VueRouter from "vue-router";
import Home from "../views/Home.vue";
import store from "@/store";

Vue.use(VueRouter);

const Board = () =>
  import(/* webpackChunkName: "board" */ "../views/Board.vue");

const Card = () => import(/* webpackChunkName: "card" */ "../views/Card.vue");

const Register = () =>
  import(/* webpackChunkName: "register" */ "../views/Register.vue");

const Login = () =>
  import(/* webpackChunkName: "login" */ "../views/Login.vue");

const NotFound = () =>
  import(/* webpackChunkName: "notfound" */ "../views/NotFound.vue");

const routes = [
  {
    path: "/",
    name: "Home",
    component: Home,
    meta: {
      needAuth: true,
    },
  },
  {
    path: "/board/:id(\\d+)",
    name: "Board",
    component: Board,
    children: [
      {
        path: "list/:listId(\\d+)/card/:cardId(\\d+)",
        name: "Card",
        component: Card,
      },
    ],
    meta: {
      needAuth: true,
    },
  },
  {
    path: "/register",
    name: "Register",
    component: Register,
  },
  {
    path: "/login",
    name: "Login",
    component: Login,
  },
  {
    path: "*",
    name: "NotFound",
    component: NotFound,
  },
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
});

/**
 * 	鉴权处理，如果该路由需要鉴权但是未携带token，引导其去
 * 	登录页
 */
router.beforeEach((to, from, next) => {
  //	可能会匹配到有子路由的情况，这时候如果有一个路由需要
  //	鉴权，则全部需要鉴权
  if (
    to.matched.some((route) => route.meta.needAuth) &&
    !store.state.user.info
  ) {
    next({ name: "Login" });
  } else {
    next();
  }
});

export default router;
